package org.abettor.util.image;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

/**
 * 图片工具类
 * @author <a href="http://www.abettor.org/" target="_blank">abettor</a>
 * 
 */
public class ImageUtil
{
	//	禁止构造实例
	private ImageUtil()
	{
	}

	/**
	 * 将图片缩放到指定尺寸
	 * @param srcImage 源图片对象
	 * @param newWidth 目标图片的宽度像素数
	 * @param newHeight 目标图片的高度像素数
	 * @return 缩放后得到的图片对象
	 */
	public static BufferedImage scale(BufferedImage srcImage, int newWidth, int newHeight)
	{
		if (newWidth <= 0 || newHeight <= 0)
		{
			return null;
		}

		int srcWidth = srcImage.getWidth();
		int srcHeight = srcImage.getHeight();

		BufferedImage tmp = new BufferedImage(newWidth, srcHeight, srcImage.getType());
		Graphics g = tmp.getGraphics();
		g.drawImage(srcImage, 0, 0, newWidth, newHeight, 0, 0, srcWidth, srcHeight, null);
		g.dispose();
		return tmp;
	}

	/**
	 * 将图片等比例缩放到一定大小
	 * @param srcImage 源图片对象
	 * @param rate 缩放倍率
	 * @return 缩放后得到的图片对象
	 */
	public static BufferedImage scale(BufferedImage srcImage, float rate)
	{
		if (rate <= 0)
		{
			return null;
		}

		int newWidth = (int) (srcImage.getWidth() * rate);
		int newHeight = (int) (srcImage.getHeight() * rate);
		return scale(srcImage, newWidth, newHeight);
	}
}
